<?php
namespace app\admin\controller;

use think\Controller;
use think\Db;
use think\Loader;
use think\Session;
use think\Url;

class Login extends Controller
{
    /**
     * 登录
     * @return string|\think\response\Json
     * @throws \think\Exception
     */
    public function index()
    {
        // 检测登录状态
        if (session('user_auth') && session('user_auth_sign')) {
            $this->redirect('Index/index');
        }

        if ($this->request->isAjax()) {
            $param = $this->request->param();

            // 验证
            $validate = Loader::validate('AdminUser');
            if (!$validate->scene('login')->check($param)) {
                return ajax_return_error($validate->getError());
            }

            //管理员信息
            $userInfo = Db::name('AdminUser')->where('user_name', $param['user_name'])->find();
            if (!$userInfo || $userInfo['password'] != encrypt($param['password'])) {
                return ajax_return_error('账号或密码错误');
            }

            $groupAccessInfo = Db::name('AuthGroupAccess')->field('group_id')->where('uid', $userInfo['uid'])->find();
            $auth = [
                'uid' => $userInfo['uid'],
                'group_id' => $groupAccessInfo['group_id'],
                'user_name' => $userInfo['user_name'],
                'last_login_time' => time(),
            ];

            $groupInfo = Db::name('AuthGroup')->where('id', $groupAccessInfo['group_id'])->find();
            $extand = [
                'title' => $groupInfo['title'],
                'headimgurl' => $userInfo['headimgurl'],
            ];

            Session::set('user_auth', array_merge($auth, $extand));
            Session::set('user_auth_sign', data_auth_sign($auth));

            //更新管理员信息
            $data = [
                'last_login_time' => time(),
                'last_login_ip' => $this->request->ip()
            ];
            Db::name('AdminUser')->where('uid', $userInfo['uid'])->update($data);
            adminLog('登录后台');

            return ajax_return('登录成功！', ['url' => Url::build('Index/index')]);
        }
        return $this->view->fetch();
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        Session::clear();
        $this->redirect('Login/index');
    }

    /*
     * 修改密码
     */
    public function changePassword()
    {
        if ($this->request->isAjax()) {
            return ajax_return_error('待开发');
        } else {
            // 判断是否登录
            if (!Session::get('user_auth') || !Session::get('user_auth_sign')) {
                $this->error('当前未登录');
            }

            $user_info = Db::name('admin_user')->where(['uid' => Session::get('user_auth.uid')])->find();

            $this->view->assign('user_info', $user_info);
            return $this->view->fetch();
        }
    }
}